#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>
using namespace std;


//father process -> read
//child process -> write
int main()
{
    //创建一个管道
    int fds[2] = {0};
    int n = pipe(fds);//fds是输出型参数
    if(n != 0)
    {
        cerr<<"pipe error"<<endl;
        return 1;
    }
    //创建子进程
    pid_t id = fork();
    //创建失败
    if(id < 0)
    {
        cerr<<"fork error"<<endl;
        //退出码设为2

        return 2;
    }
    else if(id == 0)
    {
        //子进程
        //3.关闭不需要的fd
        close(fds[0]);//子进程关闭读端
        int cnt = 0;
        while(true)
        {
            string message = "h";
            //向fds1中写入，写入message，大小是message.size()
            cnt+=write(fds[1],message.c_str(),message.size());
            cout<<"cnt:"<<cnt<<endl;
            //sleep(5);
        }
        exit(0);
    }
    if(id > 0)
    {
        //父进程
        //3.关闭不需要的fd
        char buffer[1024];
        close(fds[1]);//父进程关闭写端
        while(true)
        {
            sleep(100);
            //从fds0中读取数据读到buffer当中
            ssize_t n = read(fds[0],buffer,1024);
            if(n > 0)//读取成功
            {
                buffer[n] = 0;
                cout<<"child -> father,message: "<<buffer<<endl;
            }
        }
        //父进程会阻塞等待子进程终止
        pid_t rid = waitpid(id,nullptr,0);
        cout<<"father wait child success: "<<rid<<endl;
    }
    return 0;
}